package me.rocky.controller;

import cn.hutool.core.lang.Snowflake;
import me.rocky.document.User;
import me.rocky.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import javax.validation.Valid;

/**
 * @author Rocky
 * @version 1.0
 * @description
 * @email inaho00@foxmail.com
 * @createDate 2021/9/18 下午3:53
 * @log
 */
@RestController
@RequestMapping("/user")
public class UserController {
	@Autowired
	private UserRepository userRepository;

	@Autowired
	private Snowflake snowflake;

	@GetMapping("/")
	public Flux<User> getAll() {
		return userRepository.findAll();
	}


	@GetMapping(value = "/stream/all", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
	public Flux<User> streamGetAll() {
		return userRepository.findAll();
	}

	@PostMapping("/user")
	public Mono<User> addUser(@Valid @RequestBody  User user) {
		return userRepository.save(User.builder().age(user.getAge()).name(user.getName()).id(snowflake.nextId()).build());
	}

	@DeleteMapping("/{id}")
	public Mono<ResponseEntity<Void>> deleteUser(@Validated @PathVariable("id")Long id){
		return this.userRepository
				.findById(id)
				.flatMap(e->this.userRepository.delete(e)
						.then(Mono.just(new ResponseEntity<Void>(HttpStatus.OK)))
				)
				.defaultIfEmpty(new ResponseEntity<Void>(HttpStatus.NOT_FOUND));

	}

}
